package com.example.tourpal.model;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.example.tourpal.R;
import com.example.tourpal.model.PlanData.ConsumeEasy;
import com.example.tourpal.util.SharePreferencesManager;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**
 * @author wuliqing
 */
public class LocalDataLoader {
	private List<Person> dataArray;
	private List<Journey> userJourneys;
	private Page mPage;
	private List<Comment> comments;
	private List<PrivateMessage> messages;
	private List<String> places;
	private Journey journey;
	private Handler mHandler;
	private String mCacheDir;
	private Context mContext;
	// private static LocalDataLoader mLocalDataLoader = null;
	private SquareLishenter mSquareLishenter = null;
	private JourneyLishenter mJourneyLishenter = null;
	private CommentLishenter mCommentLishenter = null;
	private PublishJourneyLishenter mPublishJourneyLishenter = null;
	private UserJourneyLishenter mUserJourneyLishenter = null;
	private MessageRequestLishenter messageRequestLishenter = null;
	private PlaceRequestLishenter mPlaceRequestLishenter = null;
	private DeleteUserMessagesLishenter mDeleteUserMessagesLishenter = null;
	private InsertUserMessageLishenter mInsertUserMessageLishenter = null;
	private DeleteDataLishenter mDeleteDataLishenter = null;
	// private UserCollectionLishenter mUserCollectionLishenter = null;
	private ProgressDialog progressDialog = null;
	private AlertDialog alertDialog = null;
	private SharePreferencesManager mSharePreferencesManager;

	public interface SquareLishenter {
		public void requestSquareList(List<Person> persons, Page page);
	}

	public interface JourneyLishenter {
		public void requestJourneyList(Journey journey);
	}

	public interface CommentLishenter {
		public void requestCommentList(List<Comment> comments, Page page);

		public void publishCommentDone(int resultCode);
	}

	public interface PublishJourneyLishenter {
		public void requestPublishResult(int code);
	}

	public interface DeleteDataLishenter {
		public void requestDeleteResult(int code);
	}

	public interface UserJourneyLishenter {
		public void requestUserJourneyList(List<Journey> journeys);
	}

	public interface MessageRequestLishenter {
		public void requestMessageList(List<PrivateMessage> messages, Page page);
	}

	public interface DeleteUserMessagesLishenter {
		public void requestDeleteUserMessageResult(int code);
	}

	public interface PlaceRequestLishenter {
		public void requestPlaceList(List<String> places);
	}

	public interface InsertUserMessageLishenter {
		public void requestInsertUserMessageResult(int code);
	}

	// public interface UserCollectionLishenter{
	// public void requsetUserCollectionList(List<Journey> journeys);
	// }
	/**
	 * @param
	 * @return
	 */
	// public static LocalDataLoader getInstance(Context context) {
	// if (mLocalDataLoader == null) {
	// mLocalDataLoader = new LocalDataLoader(context);
	// }
	// return mLocalDataLoader;
	// }

	@SuppressLint("HandlerLeak")
	public LocalDataLoader(Context context) {
		dataArray = new ArrayList<Person>();
		userJourneys = new ArrayList<Journey>();
		journey = new Journey();
		comments = new ArrayList<Comment>();
		messages = new ArrayList<PrivateMessage>();
		places = new ArrayList<String>();
		mSharePreferencesManager = new SharePreferencesManager(context);

		progressDialog = new ProgressDialog(context);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setCancelable(true);
		progressDialog.setCanceledOnTouchOutside(false);

		mHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION:
					progressDialog.dismiss();
					break;
				case LocalDataLoaderHelp.SQUARE_START_ACTION:
					progressDialog.setMessage(mContext.getResources()
							.getString(R.string.start_download_data));
					progressDialog.show();
					break;
				case LocalDataLoaderHelp.SQUARE_DONE_ACTION:
					if (mSquareLishenter != null) {
						mSquareLishenter.requestSquareList(dataArray, mPage);
						mSquareLishenter = null;
					}
					progressDialog.dismiss();
					break;
				case LocalDataLoaderHelp.DATA_VIEW_MESSAGE_DONE_ACTION:
					if (messageRequestLishenter != null) {
						messageRequestLishenter.requestMessageList(messages,
								mPage);
						messageRequestLishenter = null;
					}
					progressDialog.dismiss();
					break;
				case LocalDataLoaderHelp.DATA_QUERY_PLACE_DONE_ACTION:
					if (mPlaceRequestLishenter != null) {
						mPlaceRequestLishenter.requestPlaceList(places);
						mPlaceRequestLishenter = null;
					}
					progressDialog.dismiss();
					break;
				case LocalDataLoaderHelp.VIEW_USER_JOURNEY_DONE_ACTION:
					if (mUserJourneyLishenter != null) {
						mUserJourneyLishenter
								.requestUserJourneyList(userJourneys);
						mUserJourneyLishenter = null;
					}
					progressDialog.dismiss();
					break;
				case LocalDataLoaderHelp.PUBLISH_USER_COLLECTION_DONE_ACTION:
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.publish_collection_success),
							Toast.LENGTH_LONG).show();
					break;
				case LocalDataLoaderHelp.PUBLISH_USER_COLLECTION_ERROR_ACTION:
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.publish_collection_error),
							Toast.LENGTH_LONG).show();
					break;
				case LocalDataLoaderHelp.DELETE_MESSAGE_SUCCESS_DONE_ACTION:
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.delete_message_success),
							Toast.LENGTH_LONG).show();
					if (mDeleteUserMessagesLishenter != null) {
						mDeleteUserMessagesLishenter
								.requestDeleteUserMessageResult(LocalDataLoaderHelp.DELETE_MESSAGE_SUCCESS_DONE_ACTION);
						mDeleteUserMessagesLishenter = null;
					} else if (mDeleteDataLishenter != null) {
						mDeleteDataLishenter
								.requestDeleteResult(LocalDataLoaderHelp.DELETE_MESSAGE_SUCCESS_DONE_ACTION);
						mDeleteDataLishenter = null;
					}
					break;
				case LocalDataLoaderHelp.DELETE_MESSAGE_ERROR_DONE_ACTION:
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.delete_message_error),
							Toast.LENGTH_LONG).show();
					if (mDeleteUserMessagesLishenter != null) {
						mDeleteUserMessagesLishenter
								.requestDeleteUserMessageResult(LocalDataLoaderHelp.DELETE_MESSAGE_ERROR_DONE_ACTION);
						mDeleteUserMessagesLishenter = null;
					} else if (mDeleteDataLishenter != null) {
						mDeleteDataLishenter
								.requestDeleteResult(LocalDataLoaderHelp.DELETE_MESSAGE_ERROR_DONE_ACTION);
						mDeleteDataLishenter = null;
					}
					break;
				case LocalDataLoaderHelp.SENDING_MESSAGE_ACTION:
					progressDialog.setMessage(mContext.getResources()
							.getString(R.string.sending_message));
					progressDialog.show();
					break;
				case LocalDataLoaderHelp.SEND_MESSAGE_SUCCESS_DONE_ACTION:
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.send_message_success),
							Toast.LENGTH_LONG).show();
					if (mInsertUserMessageLishenter != null) {
						mInsertUserMessageLishenter
								.requestInsertUserMessageResult(LocalDataLoaderHelp.SEND_MESSAGE_SUCCESS_DONE_ACTION);
						mInsertUserMessageLishenter = null;
					}
					progressDialog.dismiss();

					break;
				case LocalDataLoaderHelp.SEND_MESSAGE_ERROR_DONE_ACTION:
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.send_message_error),
							Toast.LENGTH_LONG).show();
					if (mInsertUserMessageLishenter != null) {
						mInsertUserMessageLishenter
								.requestInsertUserMessageResult(LocalDataLoaderHelp.SEND_MESSAGE_ERROR_DONE_ACTION);
						mInsertUserMessageLishenter = null;
					}
					progressDialog.dismiss();
					break;
				case LocalDataLoaderHelp.JOURNEY_START_ACTION:
					progressDialog.setMessage(mContext.getResources()
							.getString(R.string.start_download_data));
					progressDialog.show();
					break;
				case LocalDataLoaderHelp.JOURNEY_DONE_ACTION:
					if (mJourneyLishenter != null) {
						mJourneyLishenter.requestJourneyList(journey);
						mJourneyLishenter = null;
					}
					progressDialog.dismiss();
					break;
				case LocalDataLoaderHelp.COMMENT_START_ACTION:
					progressDialog.setMessage(mContext.getResources()
							.getString(R.string.start_download_data));
					progressDialog.show();
					break;
				case LocalDataLoaderHelp.COMMENT_DONE_ACTION:
					if (mCommentLishenter != null) {
						mCommentLishenter.requestCommentList(comments, mPage);
						mCommentLishenter = null;
					}
					progressDialog.dismiss();
					break;
				case LocalDataLoaderHelp.PUBLISH_JOURNEY_START_ACTION:
					progressDialog.setMessage(mContext.getResources()
							.getString(R.string.start_publish_data));
					progressDialog.show();
					break;
				case LocalDataLoaderHelp.PUBLISH_JOURNEY_DONE_ACTION:
					progressDialog.dismiss();
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.publish_journey_success),
							Toast.LENGTH_LONG).show();
					if (mPublishJourneyLishenter != null) {
						mPublishJourneyLishenter
								.requestPublishResult(LocalDataLoaderHelp.PUBLISH_JOURNEY_DONE_ACTION);
						mPublishJourneyLishenter = null;
					}
					break;
				case LocalDataLoaderHelp.PUBLISH_COMMENT_START_ACTION:
					progressDialog.setMessage(mContext.getResources()
							.getString(R.string.start_publish_comment));
					progressDialog.show();
					break;
				case LocalDataLoaderHelp.PUBLISH_COMMENT_DONE_ACTION:
					progressDialog.dismiss();
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.public_comment_success),
							Toast.LENGTH_LONG).show();
					if (mCommentLishenter != null) {
						mCommentLishenter
								.publishCommentDone(LocalDataLoaderHelp.PUBLISH_COMMENT_DONE_ACTION);
						mCommentLishenter = null;
					}
					break;
				case LocalDataLoaderHelp.PUBLISH_COMMENT_ERROR:
					progressDialog.dismiss();
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.public_comment_error),
							Toast.LENGTH_LONG).show();
					if (mCommentLishenter != null) {
						mCommentLishenter
								.publishCommentDone(LocalDataLoaderHelp.PUBLISH_COMMENT_ERROR);
						mCommentLishenter = null;
					}
					break;
				case LocalDataLoaderHelp.PUBLISH_ERROR_ACTION:
					progressDialog.dismiss();
					Toast.makeText(
							mContext,
							mContext.getResources().getString(
									R.string.publish_journey_error),
							Toast.LENGTH_LONG).show();
					if (mPublishJourneyLishenter != null) {
						mPublishJourneyLishenter
								.requestPublishResult(LocalDataLoaderHelp.PUBLISH_ERROR_ACTION);
						mPublishJourneyLishenter = null;
					}
					break;
				case LocalDataLoaderHelp.NETWORK_ERROR_ACTION:
					if (progressDialog.isShowing())
						progressDialog.dismiss();
					showAlertDialog(R.string.network_not_ok);
					if (mPublishJourneyLishenter != null) {
						mPublishJourneyLishenter
								.requestPublishResult(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
						mPublishJourneyLishenter = null;
					}
					break;
				default:
					break;
				}
			}
		};
		mContext = context;
		mCacheDir = context.getCacheDir().getAbsolutePath() + "/";
	}

	private boolean isNetworkAvailable(Context context) {
		ConnectivityManager connectivity = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity == null) {
			Log.i("NetWorkState", "Unavailabel");
			return false;
		} else {
			NetworkInfo[] info = connectivity.getAllNetworkInfo();
			if (info != null) {
				for (int i = 0; i < info.length; i++) {
					if (info[i].getState() == NetworkInfo.State.CONNECTED) {
						Log.i("NetWorkState", "Availabel");
						return true;
					}
				}
			}
		}
		return false;
	}

	private void showAlertDialog(int resId) {
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setCancelable(true);
		builder.setTitle(mContext.getResources().getString(
				R.string.alertdialog_title));
		builder.setMessage(mContext.getResources().getString(resId));
		builder.setPositiveButton(
				mContext.getResources().getString(R.string.alertdialog_ok),
				new OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						alertDialog.dismiss();
						alertDialog = null;
					}
				});
		alertDialog = builder.create();
		alertDialog.show();
	}

	@SuppressWarnings("unchecked")
	public void startLoadSquareData(final int index,
			SquareLishenter squareLishenter) {
		mSquareLishenter = squareLishenter;
		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_START_ACTION);
				if (!isNetworkAvailable(mContext)) {
					List<Person> objs = (List<Person>) readFromCache(LocalDataLoaderHelp.SQUARE_CACHE_NAME
							+ index);
					if (objs != null && objs.size() != 0) {
						dataArray.clear();
						dataArray.addAll(objs);
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_DONE_ACTION);
					}
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				String json = ServiceDataLoader
						.fecthUrl(LocalDataLoaderHelp.DATA_API_URL + index);
				if (json == null || json.length() == 0) {
//					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					//test
					List<Person> fns = new ArrayList<Person>();
					for (int i = 0; i < 20; i++) {
						fns.add(Person.getTestPerson());
					}
					dataArray.clear();
					dataArray.addAll(fns);
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_DONE_ACTION);
					return;
				}
				List<Person> fns;
				try {
					fns = parseSquareJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				dataArray.clear();
				dataArray.addAll(fns);
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_DONE_ACTION);
				writeToCache(LocalDataLoaderHelp.SQUARE_CACHE_NAME + index,
						dataArray);
			}
		}.start();
	}

	public void startQuerySquareData(final int index,
			SquareLishenter squareLishenter, final String queryWord) {
		mSquareLishenter = squareLishenter;

		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_START_ACTION);
				if (!isNetworkAvailable(mContext)) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				// String accessToken = mSharePreferencesManager
				// .readUserAccessToken();
				// if (accessToken == null) {
				// return;
				// }

				Map<String, String> params = new HashMap<String, String>();
				// params.put("method", "save");
				params.put("place", queryWord);
				// params.put("token", accessToken);
				String json = null;
				try {
					json = ServiceDataLoader.sendGetRequest(
							LocalDataLoaderHelp.DATA_API_URL + index, params);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				if (json == null || json.length() == 0) {
//					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					//test
					List<Person> fns = new ArrayList<Person>();
					for (int i = 0; i < 20; i++) {
						fns.add(Person.getTestPerson());
					}
					dataArray.clear();
					dataArray.addAll(fns);
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_DONE_ACTION);
					return;
				}
				List<Person> fns;
				try {
					fns = parseSquareJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				dataArray.clear();
				dataArray.addAll(fns);
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_DONE_ACTION);
			}
		}.start();
	}

	public void startQueryPlaceData(final String place,
			PlaceRequestLishenter mLishenter) {
		mPlaceRequestLishenter = mLishenter;
		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_START_ACTION);
				if (!isNetworkAvailable(mContext)) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				List<String> fns;
				try {
					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}

					Map<String, String> params = new HashMap<String, String>();
					params.put("token", accessToken);

					String json = ServiceDataLoader.sendGetRequest(
							LocalDataLoaderHelp.DATA_QUERY_PLACE_URL + place,
							params);
					if (json == null || json.length() == 0) {
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
						return;
					}
					fns = parsePlacesJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				places.clear();
				places.addAll(fns);
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.DATA_QUERY_PLACE_DONE_ACTION);
			}
		}.start();
	}

	/**
	 * @param page
	 *            must >= 1
	 * @param accessToken
	 *            from user class accessToken
	 * @param Lishenter
	 *            get data to main thread
	 */
	public void startLoadAllMessageData(final int page,
			MessageRequestLishenter Lishenter) {
		messageRequestLishenter = Lishenter;
		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_START_ACTION);
				if (!isNetworkAvailable(mContext)) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				String accessToken = mSharePreferencesManager
						.readUserAccessToken();
				if (accessToken == null) {
					return;
				}
				Map<String, String> params = new HashMap<String, String>();
				params.put("token", accessToken);
				String json = null;
				try {
					json = ServiceDataLoader.sendGetRequest(
							LocalDataLoaderHelp.DATA_VIEW_USER_ALL_MESSAGE_URL
									+ page, params);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				if (json == null || json.length() == 0) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				// parse json data to list
				List<PrivateMessage> fns;
				try {
					fns = parseMessageJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				messages.clear();
				messages.addAll(fns);
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.DATA_VIEW_MESSAGE_DONE_ACTION);
			}
		}.start();
	}

	public void startLoadUserToUserMessageData(final int toUserId,
			final int page, MessageRequestLishenter Lishenter) {
		messageRequestLishenter = Lishenter;
		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_START_ACTION);
				if (!isNetworkAvailable(mContext)) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				String accessToken = mSharePreferencesManager
						.readUserAccessToken();
				if (accessToken == null) {
					return;
				}
				Map<String, String> params = new HashMap<String, String>();
				params.put("token", accessToken);
				String json = null;
				try {
					json = ServiceDataLoader
							.sendGetRequest(
									LocalDataLoaderHelp.DATA_VIEW_USER_TO_USER_MESSAGE_URL
											+ toUserId + "/" + page, params);
				} catch (Exception e1) {
					e1.printStackTrace();
				}
				if (json == null || json.length() == 0) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				// parse json data to list
				List<PrivateMessage> fns;
				try {
					fns = parseMessageJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				messages.clear();
				messages.addAll(fns);
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.DATA_VIEW_MESSAGE_DONE_ACTION);
			}
		}.start();
	}

	public void startDeleteUserToUserMessageData(final int toUserId,
			DeleteUserMessagesLishenter lishenter) {
		mDeleteUserMessagesLishenter = lishenter;
		new Thread() {
			@Override
			public void run() {
				if (!isNetworkAvailable(mContext)) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				String accessToken = mSharePreferencesManager
						.readUserAccessToken();
				if (accessToken == null) {
					return;
				}
				Map<String, String> params = new HashMap<String, String>();
				params.put("token", accessToken);
				String json = null;
				try {
					json = ServiceDataLoader
							.sendGetRequest(
									LocalDataLoaderHelp.DATA_DELETE_USER_TO_USER_MESSAGE_URL
											+ toUserId, params);
					if (json == null || json.length() == 0) {
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
						return;
					}
					Message msg = new Message();
					JSONObject jsonObject = new JSONObject(json);
					String code = jsonObject.getString("code");
					if ("200".equals(code) || "201".equals(code)) {
						msg.what = LocalDataLoaderHelp.DELETE_MESSAGE_SUCCESS_DONE_ACTION;
					} else {
						msg.what = LocalDataLoaderHelp.DELETE_MESSAGE_ERROR_DONE_ACTION;
					}
					mHandler.sendMessage(msg);
				} catch (Exception e1) {
					e1.printStackTrace();
				}

				// delete success
			}
		}.start();
	}

	public void startDeleteOneMessageData(final int msgId) {
		new Thread() {
			@Override
			public void run() {
				if (!isNetworkAvailable(mContext)) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				String accessToken = mSharePreferencesManager
						.readUserAccessToken();
				if (accessToken == null) {
					return;
				}
				Map<String, String> params = new HashMap<String, String>();
				params.put("token", accessToken);
				String json = null;
				try {
					json = ServiceDataLoader.sendGetRequest(
							LocalDataLoaderHelp.DATA_DELETE_ONE_MESSAGE_URL
									+ msgId, params);
					if (json == null || json.length() == 0) {
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
						return;
					}
					// delete success
					Message msg = new Message();
					JSONObject jsonObject = new JSONObject(json);
					String code = jsonObject.getString("code");
					if ("200".equals(code) || "201".equals(code)) {
						msg.what = LocalDataLoaderHelp.DELETE_MESSAGE_SUCCESS_DONE_ACTION;
					} else {
						msg.what = LocalDataLoaderHelp.DELETE_MESSAGE_ERROR_DONE_ACTION;
					}
					mHandler.sendMessage(msg);
				} catch (Exception e1) {
					e1.printStackTrace();
				}

			}
		}.start();
	}

	public void startInsertOneMessageData(final int toUserId,
			final String content,
			InsertUserMessageLishenter insertUserMessageLishenter) {
		mInsertUserMessageLishenter = insertUserMessageLishenter;
		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SENDING_MESSAGE_ACTION);
				if (!isNetworkAvailable(mContext)) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				String accessToken = mSharePreferencesManager
						.readUserAccessToken();
				if (accessToken == null) {
					return;
				}
				List<NameValuePair> pairs = new ArrayList<NameValuePair>();
				NameValuePair pair1 = new BasicNameValuePair("token",
						accessToken);
				NameValuePair pair2 = new BasicNameValuePair("content", content);
				pairs.add(pair1);
				pairs.add(pair2);

				String json = null;
				try {
					json = ServiceDataLoader.postDataToServer(pairs,
							LocalDataLoaderHelp.DATA_INSERT_ONE_MESSAGE_URL
									+ toUserId, null);
					if (json == null || json.length() == 0) {
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
						return;
					}
					// insert success
					Message msg = new Message();
					JSONObject jsonObject = new JSONObject(json);
					String code = jsonObject.getString("code");
					if ("200".equals(code) || "201".equals(code)) {
						msg.what = LocalDataLoaderHelp.SEND_MESSAGE_SUCCESS_DONE_ACTION;
					} else {
						msg.what = LocalDataLoaderHelp.SEND_MESSAGE_ERROR_DONE_ACTION;
					}
					mHandler.sendMessage(msg);
				} catch (Exception e1) {
					e1.printStackTrace();
				}

			}
		}.start();
	}

	@SuppressWarnings("unchecked")
	public void startLoadUserJourney(UserJourneyLishenter userJourneyLishenter) {
		final int myUserid = mSharePreferencesManager.readUserId();
		mUserJourneyLishenter = userJourneyLishenter;
		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_START_ACTION);
				if (!isNetworkAvailable(mContext)) {
					List<Journey> objs = (List<Journey>) readFromCache(LocalDataLoaderHelp.USER_JOURNEY_CACHE_NAME
							+ myUserid);
					if (objs != null && objs.size() != 0) {
						userJourneys.clear();
						userJourneys.addAll(objs);
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.VIEW_USER_JOURNEY_DONE_ACTION);
					}
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				String json = ServiceDataLoader
						.fecthUrl(LocalDataLoaderHelp.DATA_VIEW_USER_JOURNEY_URL
								+ myUserid);
				if (json == null || json.length() == 0) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				List<Journey> fns;
				try {
					fns = parseUserJourneyJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				userJourneys.clear();
				userJourneys.addAll(fns);
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.VIEW_USER_JOURNEY_DONE_ACTION);
				writeToCache(LocalDataLoaderHelp.USER_JOURNEY_CACHE_NAME
						+ myUserid, userJourneys);
			}
		}.start();
	}

	/*
	 * @SuppressWarnings("unchecked") public void startLoadUserCollection(final
	 * int userId, UserCollectionLishenter userCollectionLishenter){
	 * mUserCollectionLishenter = userCollectionLishenter; new Thread() {
	 * 
	 * @Override public void run() {
	 * mHandler.sendEmptyMessage(LocalDataLoaderHelp.SQUARE_START_ACTION); if
	 * (!isNetworkAvailable(mContext)) { List<Journey> objs = (List<Journey>)
	 * readFromCache(LocalDataLoaderHelp.USER_COLLECTION_CACHE_NAME + userId);
	 * if (objs != null && objs.size() != 0) { userJourneys.clear();
	 * userJourneys.addAll(objs); mHandler.sendEmptyMessage(LocalDataLoaderHelp.
	 * VIEW_USER_COLLECTION_DONE_ACTION); }
	 * mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
	 * return; } String json = ServiceDataLoader
	 * .fecthUrl(LocalDataLoaderHelp.DATA_VIEW_USER_COLLECTION_URL + userId); if
	 * (json == null || json.length() == 0) {
	 * mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
	 * return; } List<Journey> fns; try { fns = parseUserJourneyJSON2Obj(json);
	 * } catch (Exception e) {
	 * mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
	 * return; } userJourneys.clear(); userJourneys.addAll(fns);
	 * mHandler.sendEmptyMessage
	 * (LocalDataLoaderHelp.VIEW_USER_COLLECTION_DONE_ACTION);
	 * writeToCache(LocalDataLoaderHelp.USER_COLLECTION_CACHE_NAME + userId,
	 * userJourneys); } }.start(); }
	 */

	@SuppressWarnings("unchecked")
	public void startLoadCommentData(final int planid, final int index,
			CommentLishenter commentLishenter) {
		mCommentLishenter = commentLishenter;
		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.COMMENT_START_ACTION);
				if (!isNetworkAvailable(mContext)) {
					List<Comment> objs = (List<Comment>) readFromCache(LocalDataLoaderHelp.COMMENT_CACHE_NAME
							+ index);
					if (objs != null && objs.size() != 0) {
						comments.clear();
						comments.addAll(objs);
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.COMMENT_DONE_ACTION);
					}
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}

				String json = ServiceDataLoader
						.fecthUrl(LocalDataLoaderHelp.DATA_COMMENT_VIEW
								+ planid + "/" + index);
				if (json == null || json.length() == 0) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				List<Comment> fns;
				try {
					fns = parseCommentJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				comments.clear();
				comments.addAll(fns);
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.COMMENT_DONE_ACTION);
				writeToCache(LocalDataLoaderHelp.COMMENT_CACHE_NAME + index,
						comments);
			}
		}.start();
	}

	public void startLoadJourneyData(final int journeyId,
			JourneyLishenter journeyLishenter) {
		mJourneyLishenter = journeyLishenter;
		new Thread() {
			@Override
			public void run() {
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.JOURNEY_START_ACTION);
				if (!isNetworkAvailable(mContext)) {
					Journey obj = (Journey) readFromCache(LocalDataLoaderHelp.JOURNEY_CACHE_NAME
							+ journeyId);
					if (obj != null) {
						journey = obj;
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.JOURNEY_DONE_ACTION);
					}
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
					return;
				}
				String json = ServiceDataLoader
						.fecthUrl(LocalDataLoaderHelp.DATA_JOURNEY_API_URL
								+ journeyId);
				if (json == null || json.length() == 0) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				Journey fns;
				try {
					fns = parseJourneyJSON2Obj(json);
				} catch (Exception e) {
					mHandler.sendEmptyMessage(LocalDataLoaderHelp.DOWNLOAD_ERROR_ACTION);
					return;
				}
				journey = fns;
				mHandler.sendEmptyMessage(LocalDataLoaderHelp.JOURNEY_DONE_ACTION);
				writeToCache(
						LocalDataLoaderHelp.JOURNEY_CACHE_NAME + journeyId,
						journey);
			}
		}.start();
	}

	private Journey parseJourneyJSON2Obj(String json) {
		Journey obj = new Journey();
		List<Plan> plans = new ArrayList<Plan>();
		Plan plan = new Plan();
		JsonElement element = new JsonParser().parse(json);
		JsonObject jsonObject = element.getAsJsonObject();

		JsonElement element1 = jsonObject.get("result");
		JsonObject jsonObject1 = element1.getAsJsonObject();

		try {
			obj.setDestination(jsonObject1.get("destination").getAsString());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			obj.setEndTime(jsonObject1.get("endTime").getAsString());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			obj.setId(jsonObject1.get("id").getAsInt());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			obj.setIspublic(jsonObject1.get("ispublic").getAsInt());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			obj.setName(jsonObject1.get("name").getAsString());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			obj.setPraiseNum(jsonObject1.get("praiseNum").getAsInt());
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			obj.setStartTime(jsonObject1.get("startTime").getAsString());
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		JsonArray array = jsonObject1.get("plans").getAsJsonArray();

		Iterator<JsonElement> it = array.iterator();
		Gson gson = new Gson();
		while (it.hasNext()) {
			JsonElement e = it.next();
			plan = gson.fromJson(e, Plan.class);
			Collections.sort(plan.getConsumes());
			plans.add(plan);
		}
		Collections.sort(plans);
		obj.setPlans(plans);
		return obj;
	}

	// JSONObject jsonObject = new JSONObject(json).getJSONObject("page");
	// pageCount = jsonObject.getString("pageCount");
	private List<Person> parseSquareJSON2Obj(String json) {
		List<Person> objs = new ArrayList<Person>();
		Person obj = null;
		JsonElement element = new JsonParser().parse(json);
		JsonArray array = element.getAsJsonObject().get("result")
				.getAsJsonArray();

		mPage = null;
		mPage = new Page();
		JsonElement pageJsonElement = element.getAsJsonObject().get("page");

		Iterator<JsonElement> it = array.iterator();
		Gson gson = new Gson();

		mPage = gson.fromJson(pageJsonElement, Page.class);

		while (it.hasNext()) {
			JsonElement e = it.next();
			obj = gson.fromJson(e, Person.class);
			objs.add(obj);
		}
		return objs;
	}

	private List<Journey> parseUserJourneyJSON2Obj(String json) {
		List<Journey> objs = new ArrayList<Journey>();
		Journey obj = null;
		JsonElement element = new JsonParser().parse(json);
		JsonArray array = element.getAsJsonObject().get("result")
				.getAsJsonArray();
		Iterator<JsonElement> it = array.iterator();
		Gson gson = new Gson();
		while (it.hasNext()) {
			JsonElement e = it.next();
			obj = gson.fromJson(e, Journey.class);
			objs.add(obj);
		}
		return objs;
	}

	private List<PrivateMessage> parseMessageJSON2Obj(String json) {
		List<PrivateMessage> objs = new ArrayList<PrivateMessage>();
		PrivateMessage obj = null;
		JsonElement element = new JsonParser().parse(json);
		JsonArray array = element.getAsJsonObject().get("result")
				.getAsJsonArray();
		Iterator<JsonElement> it = array.iterator();
		Gson gson = new Gson();

		mPage = null;
		mPage = new Page();
		JsonElement pageJsonElement = element.getAsJsonObject().get("page");
		mPage = gson.fromJson(pageJsonElement, Page.class);

		while (it.hasNext()) {
			JsonElement e = it.next();
			obj = gson.fromJson(e, PrivateMessage.class);
			objs.add(obj);
		}
		return objs;
	}

	private List<String> parsePlacesJSON2Obj(String json) {
		List<String> objs = new ArrayList<String>();
		String obj = null;
		JsonElement element = new JsonParser().parse(json);
		JsonArray array = element.getAsJsonObject().get("result")
				.getAsJsonArray();
		Iterator<JsonElement> it = array.iterator();
		Gson gson = new Gson();
		while (it.hasNext()) {
			JsonElement e = it.next();
			obj = gson.fromJson(e, String.class);
			objs.add(obj);
		}
		return objs;
	}

	private void parsePage(String json) {
		mPage = null;
		mPage = new Page();
		try {
			JSONObject jsonObject = new JSONObject(json).getJSONObject("page");
			mPage.setPageCount(jsonObject.getInt("pageCount"));
			mPage.setPageNo(jsonObject.getInt("pageNo"));
			mPage.setPageSize(jsonObject.getInt("pageSize"));
			mPage.setRowCount(jsonObject.getInt("rowCount"));
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
	}

	private List<Comment> parseCommentJSON2Obj(String json) {
		List<Comment> objs = new ArrayList<Comment>();
		Comment obj = null;
		JsonElement element = new JsonParser().parse(json);
		JsonArray array = element.getAsJsonObject().get("result")
				.getAsJsonArray();
		parsePage(json);
		Iterator<JsonElement> it = array.iterator();
		Gson gson = new Gson();
		while (it.hasNext()) {
			JsonElement e = it.next();
			obj = gson.fromJson(e, Comment.class);
			objs.add(obj);
		}
		return objs;
	}

	public void publishDeletePlanType(final int planId, final int type) {
		mHandler.sendEmptyMessage(1);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					List<NameValuePair> nvs = new ArrayList<NameValuePair>();
					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}
					NameValuePair pair = new BasicNameValuePair("token",
							accessToken);
					nvs.add(pair);
					String res = ServiceDataLoader.deleteDataToServer(nvs,
							LocalDataLoaderHelp.DATA_DELETE_JOURNEY_TYPE_URL
									+ planId + "/" + type);
					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("delete_journry_type_key", res);
					msg.setData(bundle);
					msg.what = 2;
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					Log.e("", e.toString());
				}

			}
		}).start();
	}

	public void publishDeletePlan(final int planId) {
		mHandler.sendEmptyMessage(1);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					List<NameValuePair> nvs = new ArrayList<NameValuePair>();
					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}
					NameValuePair pair = new BasicNameValuePair("token",
							accessToken);
					nvs.add(pair);
					String res = ServiceDataLoader.deleteDataToServer(nvs,
							LocalDataLoaderHelp.DATA_DELETE_PLAN_URL + planId);
					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("delete_plan_key", res);
					msg.setData(bundle);
					msg.what = 2;
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					Log.e("", e.toString());
				}

			}
		}).start();
	}

	public void publishDeleteJourney(final int journeyId,
			DeleteDataLishenter dataLishenter) {
		mDeleteDataLishenter = dataLishenter;
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					if (!isNetworkAvailable(mContext)) {
						mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
						return;
					}
					// List<NameValuePair> nvs = new ArrayList<NameValuePair>();
					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}
					// NameValuePair pair = new BasicNameValuePair("token",
					// accessToken);
					// nvs.add(pair);
					Map<String, String> params = new HashMap<String, String>();
					params.put("token", accessToken);
					String res = ServiceDataLoader.deleteDataToServer(
							LocalDataLoaderHelp.DATA_DELETE_JOURNEY_URL
									+ journeyId, params);

					JSONObject jsonObject = new JSONObject(res);
					String code = jsonObject.getString("code");

					Message msg = new Message();
					if ("200".equals(code) || "201".equals(code)) {
						msg.what = LocalDataLoaderHelp.DELETE_MESSAGE_SUCCESS_DONE_ACTION;
					} else {
						msg.what = LocalDataLoaderHelp.DELETE_MESSAGE_ERROR_DONE_ACTION;
					}
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					Log.e("", e.toString());
				}

			}
		}).start();
	}

	public void publishDeleteComment(final int commentId) {
		mHandler.sendEmptyMessage(1);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					List<NameValuePair> nvs = new ArrayList<NameValuePair>();
					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}
					NameValuePair pair = new BasicNameValuePair("token",
							accessToken);
					nvs.add(pair);
					String res = ServiceDataLoader.deleteDataToServer(nvs,
							LocalDataLoaderHelp.DATA_DELETE_COMMENT_URL
									+ commentId);
					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("delete_comment_key", res);
					msg.setData(bundle);
					msg.what = 2;
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					Log.e("", e.toString());
				}

			}
		}).start();
	}

	public void publishCollection(final int userId, final int journeyId) {
		// mHandler.sendEmptyMessage(1);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					List<NameValuePair> nvs = new ArrayList<NameValuePair>();
					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}
					NameValuePair pair = new BasicNameValuePair("token",
							accessToken);
					nvs.add(pair);

					String res = ServiceDataLoader.postDataToServer(nvs,
							LocalDataLoaderHelp.DATA_ADD_USER_COLLECTION_URL
									+ userId + "/" + journeyId, "put");
					JSONObject jsonObject = new JSONObject(res);
					String code = jsonObject.getString("code");

					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("journey_key", res);
					msg.setData(bundle);
					if ("200".equals(code) || "201".equals(code)) {
						msg.what = LocalDataLoaderHelp.PUBLISH_USER_COLLECTION_DONE_ACTION;
					} else {
						msg.what = LocalDataLoaderHelp.PUBLISH_USER_COLLECTION_ERROR_ACTION;
					}
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					Log.e("", e.toString());
				}

			}
		}).start();
	}

	public void publishPraise(final int planId, final int userId) {
		mHandler.sendEmptyMessage(1);
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					List<NameValuePair> nvs = new ArrayList<NameValuePair>();
					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}
					NameValuePair pair = new BasicNameValuePair("token",
							accessToken);
					nvs.add(pair);
					String res = ServiceDataLoader.putDataToServer(nvs,
							LocalDataLoaderHelp.DATA_ADD_PRAISE_URL + planId
									+ "/" + userId, "put");
					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("journey_key", res);
					msg.setData(bundle);
					msg.what = 2;
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					Log.e("", e.toString());
				}

			}
		}).start();
	}

	private String getPushTimeHelp(String time) {
		try {
			SimpleDateFormat dateFormat0 = new SimpleDateFormat("yyyy/MM/dd",
					Locale.CHINA);
			Date date = dateFormat0.parse(time);

			SimpleDateFormat dateFormat = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss", Locale.CHINA);

			Calendar calendar = Calendar.getInstance();
			calendar.setTime(date);
			calendar.set(Calendar.HOUR, 0);
			calendar.set(Calendar.MINUTE, 0);
			calendar.set(Calendar.SECOND, 0);

			String newTime = dateFormat.format(calendar.getTime());
			return newTime;
		} catch (ParseException e) {
			e.printStackTrace();
			// 20150210 ->2015-02-10 00:00:00
			StringBuilder sb = new StringBuilder();
			sb.append(time.substring(0, 4)).append("-")
					.append(time.substring(4, 6)).append("-")
					.append(time.substring(6, 8)).append(" 00:00:00");
			return sb.toString();
		}
	}

	public JourneyData doJourneyToPublish(Journey journey) {
		JourneyData journeyData = new JourneyData();
		journeyData.setDestination(journey.getDestination());
		journeyData.setEndTime(getPushTimeHelp(journey.getEndTime()));
		journeyData.setStartTime(getPushTimeHelp(journey.getStartTime()));
		journeyData.setName(journey.getName());
		journeyData.setUser(journey.getUser());
		journeyData.setId(journey.getId());
		journeyData.setDelFlg(journey.getDelFlg());
		List<PlanData> plans = new ArrayList<PlanData>();
		for (Plan plan : journey.getPlans()) {
			PlanData planData = new PlanData();
			planData.setName(plan.getName());
			planData.setDescription(plan.getDescription());
			planData.setEndTime(getPushTimeHelp(plan.getEndTime()));
			planData.setStartTime(getPushTimeHelp(plan.getStartTime()));
			planData.setIspublic(plan.getIspublic());
			planData.setPlanOrder(plan.getPlanOrder());
			planData.setPlanId(plan.getId());
			planData.setDelFlg(plan.getDelFlg());
			for (Consume consume : plan.getConsumes()) {
				ConsumeEasy consumeEasy = new ConsumeEasy();
				consumeEasy.setClassOrder(consume.getClassOrder());
				consumeEasy.setDescription(consume.getDescription());
				consumeEasy.setType(consume.getType());
				consumeEasy.setCreateTime(consume.getCreateTime());
				consumeEasy.setDelFlg(consume.getDeflg());
				switch (consume.getType()) {
				case 1:
					planData.getEats().add(consumeEasy);
					break;
				case 2:
					planData.getHotels().add(consumeEasy);
					break;
				case 3:
					planData.getTrffics().add(consumeEasy);
					break;
				case 4:
					planData.getTours().add(consumeEasy);
					break;
				case 5:
					planData.getRecreations().add(consumeEasy);
					break;
				case 6:
					planData.getShoppings().add(consumeEasy);
					break;
				case 7:
					planData.getOthers().add(consumeEasy);
					break;
				default:
					break;
				}
			}
			plans.add(planData);
		}
		journeyData.setPlans(plans);
		return journeyData;
	}

	public void publishJourney(Journey journey,
			PublishJourneyLishenter journeyLishenter) {
		mPublishJourneyLishenter = journeyLishenter;
		if (!isNetworkAvailable(mContext)) {
			mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
			return;
		}
		final JourneyData journeyData = doJourneyToPublish(journey);
		mHandler.sendEmptyMessage(LocalDataLoaderHelp.PUBLISH_JOURNEY_START_ACTION);
		new Thread(new Runnable() {
			@Override
			public void run() {
				List<NameValuePair> nvs = new ArrayList<NameValuePair>();
				try {
					Gson g = new Gson();

					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}
					NameValuePair pair = new BasicNameValuePair("token",
							accessToken);

					nvs.add(new BasicNameValuePair("json", g
							.toJson(journeyData)));
					nvs.add(pair);

					String res = ServiceDataLoader.postDataToServer(nvs,
							LocalDataLoaderHelp.PUBLISH_JOURNEY_URL, "request");

					JSONObject jsonObject = new JSONObject(res);
					String code = jsonObject.getString("code");

					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("journey_key", res);
					msg.setData(bundle);
					if ("200".equals(code) || "201".equals(code)) {
						msg.what = LocalDataLoaderHelp.PUBLISH_JOURNEY_DONE_ACTION;
					} else {
						msg.what = LocalDataLoaderHelp.PUBLISH_ERROR_ACTION;
					}
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					Log.e("", e.toString());
				}

			}
		}).start();
	}

	public void publishComment(final Comment obj, final int journeyid,
			CommentLishenter commentLishenter) {
		if (!isNetworkAvailable(mContext)) {
			mHandler.sendEmptyMessage(LocalDataLoaderHelp.NETWORK_ERROR_ACTION);
			return;
		}
		mCommentLishenter = commentLishenter;
		mHandler.sendEmptyMessage(LocalDataLoaderHelp.PUBLISH_COMMENT_START_ACTION);
		new Thread(new Runnable() {
			@Override
			public void run() {
				List<NameValuePair> nvs = new ArrayList<NameValuePair>();
				try {
					JSONObject jsonObject = new JSONObject();
					jsonObject.put("createTime", obj.getCreateTime());
					// jsonObject.put("id", obj.getId());
					jsonObject.put("userId", obj.getUserId());
					jsonObject.put("planId", obj.getPlanId());
					jsonObject.put("planComment", obj.getPlanComment());
					jsonObject.put("userNikeName", obj.getUserNikeName());

					nvs.add(new BasicNameValuePair("json", jsonObject
							.toString()));

					String accessToken = mSharePreferencesManager
							.readUserAccessToken();
					if (accessToken == null) {
						return;
					}
					NameValuePair pair = new BasicNameValuePair("token",
							accessToken);
					nvs.add(pair);

					String res = ServiceDataLoader.postDataToServer(nvs,
							LocalDataLoaderHelp.ADD_DATA_API_URL + journeyid,
							null);

					JSONObject jsonObject2 = new JSONObject(res);
					String code = jsonObject2.getString("code");

					Message msg = new Message();
					Bundle bundle = new Bundle();
					bundle.putString("comment_key", res);
					msg.setData(bundle);
					if ("200".equals(code) || "201".equals(code)) {
						msg.what = LocalDataLoaderHelp.PUBLISH_COMMENT_DONE_ACTION;
					} else {
						msg.what = LocalDataLoaderHelp.PUBLISH_COMMENT_ERROR;
					}
					mHandler.sendMessage(msg);
				} catch (Exception e) {
					Log.e("", e.toString());
				}

			}
		}).start();
	}

	public void writeToCache(String cacheKey, Object cacheValue) {
		int cnt = 0;
		do {
			try {
				File destDir = new File(mCacheDir);
				if (!destDir.exists()) {
					destDir.mkdirs();
				}
				ObjectOutputStream os = new ObjectOutputStream(
						new FileOutputStream(mCacheDir + cacheKey));
				os.writeObject(cacheValue);
				os.close();
				break;
			} catch (Exception e) {
				cnt++;
			}
		} while (cnt < ServiceDataLoader.MAX_FAILCOUNT);

	}

	/**
	 * List<Person> objs = (List<Person>)robot.readFromCache("Person");
	 * */
	public Object readFromCache(String cacheKey) {
		File file = new File(mCacheDir + cacheKey);
		if (!file.exists()) {
			return null;
		}

		Object cacheObj = null;
		int cnt = 0;
		do {
			try {
				ObjectInputStream is = new ObjectInputStream(
						new FileInputStream(file));
				cacheObj = is.readObject();
				is.close();
				break;
			} catch (Exception e) {
				e.printStackTrace();
				cnt++;
			}
		} while (cnt < ServiceDataLoader.MAX_FAILCOUNT);
		return cacheObj;
	}

	// -----------------------------------------------------------------------------------about
	// image
	public interface ImageCallback {
		public void obtainImage(Bitmap bitmap);
	}

	private ImageCallback mCallback = null;

	public void setImageCallback(ImageCallback callback) {
		mCallback = callback;
	}

	/**
	 * get bitmap
	 * 
	 * @param context
	 * @param fileName
	 * @return
	 */
	private Bitmap getBitmap(Context context, String fileName) {

		String filepath = context.getFilesDir() + File.separator + fileName;
		File file = new File(filepath);
		if (!file.exists()) {
			return null;
		}

		FileInputStream fis = null;
		Bitmap bitmap = null;
		try {
			fis = context.openFileInput(fileName);
			bitmap = BitmapFactory.decodeStream(fis);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
			} catch (Exception e) {
			}
		}
		return bitmap;
	}

	private boolean isEmpty(String input) {
		if (input == null || "".equals(input))
			return true;

		for (int i = 0; i < input.length(); i++) {
			char c = input.charAt(i);
			if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
				return false;
			}
		}
		return true;
	}

	private String getFileName(String filePath) {
		if (isEmpty(filePath))
			return "";
		return filePath.replaceAll("(http://|https://|\\.|/)", "");
	}

	@SuppressLint("HandlerLeak")
	final Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			Bitmap bitmap = (Bitmap) msg.obj;
			if (mCallback != null) {
				mCallback.obtainImage(bitmap);
			}

			super.handleMessage(msg);
		}

	};

	public void loadPhoto(Person obj, ImageCallback callback) {
		mCallback = callback;

		if (obj.getHeadPortrait().length() > 0) {
			Bitmap bitmap = getBitmap(mContext,
					getFileName(obj.getHeadPortrait()));
			if (bitmap == null) {
				Log.e("TAG", "downing");
				toDown(obj);
			} else {
				Log.e("TAG", "exist");
				if (mCallback != null) {
					mCallback.obtainImage(bitmap);
				}
			}
		}
	}

	/**
	 * save /data/data/PACKAGE_NAME/files
	 * 
	 * @throws IOException
	 */
	private void saveImage(Context context, String fileName, Bitmap bitmap)
			throws IOException {
		saveImage(context, fileName, bitmap, 100);
	}

	private void saveImage(Context context, String fileName, Bitmap bitmap,
			int quality) throws IOException {
		if (bitmap == null || fileName == null || context == null)
			return;

		FileOutputStream fos = context.openFileOutput(fileName,
				Context.MODE_PRIVATE);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, quality, stream);
		byte[] bytes = stream.toByteArray();
		fos.write(bytes);
		fos.close();
	}

	private void toDown(final Person obj) {
		new Thread(new Runnable() {
			@Override
			public void run() {
				Bitmap bitmap = ServiceDataLoader.downNetImage(obj
						.getHeadPortrait());
				if (bitmap == null) {
					Log.e("TAG", "null bitmap");
					return;
				}

				Message msg = new Message();
				msg.what = 0;
				msg.obj = bitmap;
				handler.sendMessage(msg);

				try {
					saveImage(mContext, getFileName(obj.getHeadPortrait()),
							bitmap);
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}).start();
	}
}
